package com.example.bank.controller;

import cn.hutool.core.util.ObjectUtil;
import com.example.bank.domain.Result;
import com.example.bank.pojo.Client;
import com.example.bank.pojo.record.Response;
import com.example.bank.service.client.ClientService;
import com.example.bank.service.result.ResultService;
import com.example.bank.util.InterceptorUtil;
import com.example.bank.util.ResultUtil;
import com.google.gson.Gson;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author ：Leeziqiang
 * @description：TODO
 * @date ：2022/1/17 22:08
 */
@RestController
@RequestMapping("/interface")
public class InterceptorController {

    private static final Logger logger = LoggerFactory.getLogger(InterceptorController.class);

    @Autowired
    private ClientService clientService;
    @Autowired
    private ResultService resultService;


    @PostMapping("/accident")
    public String getAccidentRecord(String clientId) throws IOException {
        Client client = clientService.findById(clientId);
        return InterceptorUtil.accidentRecord(client.getCarNumber());
    }

    @PostMapping("/maintain")
    public String getMaintainRecord(String clientId) throws IOException {
        Client client = clientService.findById(clientId);
        // 改变查询状态
        clientService.updateQueryState(clientId);
        return InterceptorUtil.maintainRecord(client.getEngineNumber(), client.getCarNumber());
    }

    @PostMapping("/record")
    public String record(HttpServletRequest request) {
        String info = (String) request.getParameter("response");
        Gson gson = new Gson();
        Response response = gson.fromJson(info, Response.class);
        com.example.bank.pojo.record.Result result = response.getResult();
        // 车辆大架号
        String vin = response.getVin();
        // 将返回结果保存到数据库
        boolean flag = resultService.saveResult(vin, result);
        if (flag) {
            return "success";
        }
        return "error";

    }

    @PostMapping("/showRecord")
    public Result showRecord(String clientId) {
        Client client = clientService.findById(clientId);
        String vin = client.getCarNumber();
        com.example.bank.pojo.record.Result result = resultService.findById(vin);
        if (ObjectUtil.isNotNull(result)) {
            return ResultUtil.success(result);
        }
        return ResultUtil.error("尚未查到，请耐心等待");
    }
}
